package com.cjjd.c.feature.home.chekin.select_detail;

import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.cjjd.c.EventBusKeys;
import com.cjjd.c.R;
import com.cjjd.c.ShareKeys;
import com.cjjd.c.base.ActionBarActivity;
import com.cjjd.c.bean.CheckInDetailBean;
import com.cjjd.c.bean.HttpResult;
import com.cjjd.c.bean.ListResult;
import com.cjjd.c.bean.SelectHomeDetailItemBean;
import com.cjjd.c.bean.SelectHomeOrderDetailBean;
import com.cjjd.c.bean.TravellerListBean;
import com.cjjd.c.feature.home.chekin.select_people.SelectPeopleActivity;
import com.cjjd.c.http.CallbackImpl;
import com.cjjd.c.http.JsonUtils;
import com.cjjd.c.utils.ImageUtil;
import com.cjjd.c.utils.LogUtil;
import com.cjjd.c.utils.SharePrefUtil;
import com.cjjd.c.utils.ToastUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Response;

/**
 * Created by Administrator on 2017/9/24.
 * 确认选房
 */

public class SelectHomeActivity extends ActionBarActivity {
    //TODO 缺少房型图片
    @Bind(R.id.iv_home)
    ImageView ivHome;

    @Bind(R.id.cb_title_build)
    CheckBox cbTitleBuild;
    @Bind(R.id.recycleview_build_select)
    RecyclerView recycleviewBuildSelect;

    @Bind(R.id.cb_title_floor)
    CheckBox cbTitleFloor;
    @Bind(R.id.recycleview_floor_select)
    RecyclerView recycleviewFloorSelect;

    @Bind(R.id.recycleview_horizontal)
    RecyclerView recycleview_horizontal;

    private SelectHomeOrderDetailBean selectHomeOrderDetailBean;
    private SelectHomeHorizontalAdapter selectHomeHorizontalAdapter;

    private SelectHomeHorizontalAdapter selectHomeHorizontalAdapter1;
    private SelectHomeHorizontalAdapter selectHomeHorizontalAdapter2;

    @Override
    public Object getTitleString() {
        return " ";
    }

    @Override
    public int getContentView() {
        return R.layout.fragment_select_home;
    }

    // 获取到的楼栋楼层信息
    List<CheckInDetailBean.HotelFloor> hotelFloorList = new ArrayList<>();
    // 楼栋
    private ArrayList<CheckInDetailBean.HotelFloor.HotelItemFloorItem> buildItemList = new ArrayList<>();
    // 楼层
    private ArrayList<CheckInDetailBean.HotelFloor.HotelItemFloorItem> floorItemList = new ArrayList<>();

    // 根据筛选结果选出来的房间
    private ArrayList<SelectHomeDetailItemBean> homeListData = new ArrayList<>();
    private ArrayList<SelectHomeDetailItemBean> selectHomeList = new ArrayList<>();


    public static final int from_query_build = 0x00000001;
    public static final int from_query_floor = 0x00000002;
    public static final int from_result = 0x00000003;

    private void initView() {


        // 楼层
        LinearLayoutManager linearLayoutManager2 = new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false);
        selectHomeHorizontalAdapter2 = new SelectHomeHorizontalAdapter(mContext, floorItemList, R.layout.item_home_select, from_query_floor);
        recycleviewFloorSelect.setAdapter(selectHomeHorizontalAdapter2);
        recycleviewFloorSelect.setLayoutManager(linearLayoutManager2);

        // 楼栋
        LinearLayoutManager linearLayoutManager1 = new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false);
        selectHomeHorizontalAdapter1 = new SelectHomeHorizontalAdapter(mContext, buildItemList, R.layout.item_home_select, from_query_build);
        selectHomeHorizontalAdapter1.setAllData(hotelFloorList, floorItemList, selectHomeHorizontalAdapter2);
        recycleviewBuildSelect.setAdapter(selectHomeHorizontalAdapter1);
        recycleviewBuildSelect.setLayoutManager(linearLayoutManager1);


        // 筛选结果
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false);
        selectHomeHorizontalAdapter = new SelectHomeHorizontalAdapter(mContext, homeListData, R.layout.item_home_select, from_result);
        selectHomeHorizontalAdapter.setSelectType(select_type);
        selectHomeHorizontalAdapter.setSelectedTravellerNum(selectedTravellerList.size());
        recycleview_horizontal.setAdapter(selectHomeHorizontalAdapter);
        recycleview_horizontal.setLayoutManager(linearLayoutManager);


        cbTitleBuild.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    // 展开
                    cbTitleBuild.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.icon_arrow_down, 0);
                    recycleviewBuildSelect.setVisibility(View.VISIBLE);
                } else {
                    cbTitleBuild.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.icon_arrow_up, 0);
                    recycleviewBuildSelect.setVisibility(View.GONE);
                }
            }
        });


        cbTitleFloor.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    // 展开
                    boolean can = false;
                    for (CheckInDetailBean.HotelFloor.HotelItemFloorItem item : buildItemList) {
                        if (item.isSelected) can = true;
                    }

                    if (can) {
                        cbTitleFloor.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.icon_arrow_down, 0);
                        recycleviewFloorSelect.setVisibility(View.VISIBLE);
                    } else {
                        cbTitleFloor.setChecked(false);
                        ToastUtil.showToast("请先选择楼栋");
                    }
                } else {
                    cbTitleFloor.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.icon_arrow_up, 0);
                    recycleviewFloorSelect.setVisibility(View.GONE);
                }
            }
        });

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        getIntentData();
        getOrderDetail();
        getCheckinDetail();
        initView();
        getOptionalRoomList();
    }

    /**
     * 获取可选择的楼栋和楼层信息
     */
    private void getCheckinDetail() {
        HashMap<String, Object> h1 = new HashMap<>();
        h1.put("token", SharePrefUtil.getString(mContext, ShareKeys.Token, ""));
        h1.put("sessionId", SharePrefUtil.getString(mContext, ShareKeys.sessionId, ""));
        h1.put("orderUuid", SharePrefUtil.getString(mContext, ShareKeys.orderMainUuid, ""));                 // 预订单主表uuid
        h1.put("orderDetailUuid", SharePrefUtil.getString(mContext, ShareKeys.orderDetailUuid, ""));         // 预订单明细uuid

        Call<HttpResult<CheckInDetailBean>> call = service.checkIn(JsonUtils.convertParam("checkIn", h1));
        call.enqueue(new CallbackImpl<CheckInDetailBean>() {
            @Override
            public void responseSuccess(Call<HttpResult<CheckInDetailBean>> call, Response<HttpResult<CheckInDetailBean>> response) {

                if (hotelFloorList.size() > 0) {
                    hotelFloorList.clear();
                }

                hotelFloorList.addAll(response.body().getData().dataList);

                ImageUtil.displayImage(response.body().getData().order.roomTypeImg, ivHome);

                changeSelectInfo();

            }
        });
    }

    /**
     * 获取到数据后，进行可选项设置
     */
    private void changeSelectInfo() {

        // 构造楼栋信息。 只有选择了楼栋信息之后， 才能选择楼层信息。
        int buildSize = hotelFloorList.size();
        for (int buildI = 0; buildI < buildSize; buildI++) {
            buildItemList.add(hotelFloorList.get(buildI).build);
        }
        //  2017/12/25 如果只有一栋楼，则默认选择
        if (buildSize == 1) {
            buildItemList.get(0).isSelected = true;
        }
        selectHomeHorizontalAdapter1.notifyDataSetChanged();
    }


    private int select_type = -1;
    private String orderMainUuid;
    private String orderDetailUuid;
    private List<TravellerListBean> selectedTravellerList = new ArrayList<>();
    private List<String> orderDetailUuidslist = new ArrayList<>();

    private void getIntentData() {
        select_type = getIntent().getIntExtra("selectType", -1);
        orderMainUuid = getIntent().getStringExtra("orderMainUuid");
        orderDetailUuid = getIntent().getStringExtra("orderDetailUuid");
        LogUtil.e("xyd", "SelectHomeActivity   orderMainUuid = " + orderMainUuid);
        selectedTravellerList = (List<TravellerListBean>) getIntent().getSerializableExtra("selectedTravellerList");
        orderDetailUuidslist = (List<String>) getIntent().getSerializableExtra("orderDetailUuidslist");

        if (orderDetailUuidslist != null) {
            LogUtil.e("xyd", "orderDetailUuidList is " + orderDetailUuidslist.size());
            LogUtil.e("xyd", "selectedTravellerList is " + selectedTravellerList.size());
            if (selectedTravellerList.size() == 1) {
                LogUtil.e("xyd", "选房人=" + selectedTravellerList.get(0).name);
                mActionBar.setTitle(selectedTravellerList.get(0).name + "的房间");
            }
        }

        if (select_type == SelectPeopleActivity.SELECT_MULTI) {
            mActionBar.setTitle("批量选房任务");
        }
    }

    // 可选房间列表
    private void getOptionalRoomList() {
        HashMap<String, Object> h1 = new HashMap<>();
        h1.put("token", SharePrefUtil.getString(mContext, ShareKeys.Token, ""));
        h1.put("sessionId", SharePrefUtil.getString(mContext, ShareKeys.sessionId, ""));
        h1.put("hotelUuid", SharePrefUtil.getString(mContext, ShareKeys.hotelUuid));
        h1.put("orderUuid", orderMainUuid);

        h1.put("nowPage", 1 + "");                    // 非必填
        h1.put("pageShow", 100 + "");                 // 非必填

        String floorQueqy = "";
        for (CheckInDetailBean.HotelFloor.HotelItemFloorItem item : floorItemList) {
            if (item.isSelected) {
                floorQueqy = item.id;
            }
        }
        h1.put("floor", floorQueqy);                         // 非必填

        //h1.put("orientation", "1");                   // 非必填
        //h1.put("mum", "1");                           // 非必填
        //h1.put("isSmoke", "1");                       // 非必填

        Call<HttpResult<ListResult<SelectHomeDetailItemBean>>> call = service.getOptionalRoomList(JsonUtils.convertParam("getOptionalRoomList", h1));
        call.enqueue(new CallbackImpl<ListResult<SelectHomeDetailItemBean>>() {
            @Override
            public void responseSuccess(Call<HttpResult<ListResult<SelectHomeDetailItemBean>>> call, Response<HttpResult<ListResult<SelectHomeDetailItemBean>>> response) {
                if (homeListData.size() > 0) {
                    homeListData.clear();
                }

                homeListData.addAll(response.body().getData().dataList);
                selectHomeHorizontalAdapter.notifyDataSetChanged();
            }
        });
    }

    // 获取单个人选择时候的房子详情
    private void getOrderDetail() {
        HashMap<String, Object> h1 = new HashMap<>();
        h1.put("token", SharePrefUtil.getString(mContext, ShareKeys.Token, ""));
        h1.put("sessionId", SharePrefUtil.getString(mContext, ShareKeys.sessionId, ""));
        h1.put("orderDetailUuid", orderDetailUuidslist.get(0));       // 订单房间明细uuid

        Call<HttpResult<SelectHomeOrderDetailBean>> call = service.getOrderDetail(JsonUtils.convertParam("getOrderDetail", h1));
        call.enqueue(new CallbackImpl<SelectHomeOrderDetailBean>() {
            @Override
            public void responseSuccess(Call<HttpResult<SelectHomeOrderDetailBean>> call, Response<HttpResult<SelectHomeOrderDetailBean>> response) {
                //　改变房间状态
                selectHomeOrderDetailBean = response.body().getData();
                changeUI(selectHomeOrderDetailBean);
            }
        });
    }

    @Bind(R.id.chuangname)
    TextView tvchuangname;
    @Bind(R.id.rulidianriqi)
    TextView tvrulidianriqi;
    @Bind(R.id.fangjianqingkuang)
    TextView tvfangjianqingkuang;

    private void changeUI(SelectHomeOrderDetailBean bean) {

        // TODO: 2017/9/24 设置其他信息
        tvchuangname.setText(bean.detail.roomTypeName);
        String checinTime = bean.detail.checkInDate.length() < 10 ? bean.detail.checkInDate : bean.detail.checkInDate.substring(0, 10);
        String checoutTime = bean.detail.checkOutDate.length() < 10 ? bean.detail.checkOutDate : bean.detail.checkOutDate.substring(0, 10);
        tvrulidianriqi.setText("入住：" + checinTime
                + "  离店：" + checoutTime + "   " + bean.detail.checkInDayNum + "晚");
        tvfangjianqingkuang.setText("");
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        ButterKnife.unbind(this);
    }

    @OnClick(R.id.tv_next)
    public void onViewClicked() {
        if (selectHomeList.size() > 0) {
            selectHomeList.clear();
        }
        for (SelectHomeDetailItemBean item : homeListData) {
            if (item.isSelected()) {
                selectHomeList.add(item);
            }
        }
        LogUtil.e("xyd", "已经选择的房间有几间：" + selectHomeList.size());
        if (select_type == SelectPeopleActivity.SELECT_MULTI) {
            // 多选项状态下，可以选子集
            if (selectHomeList.size() == 0) {
                ToastUtil.showToast("请选择房间");
                return;
            }
        }

        // 构造数据  已选择房间个数，一定要和联系人，待选择房间的个数 保持一致， 这时候要手动处理 联系人和待选房间的数据。
        // 已经选择房间的
        int selectHomeNum = selectHomeList.size();
        StringBuffer roomUuids = new StringBuffer();
        for (int i = 0; i < selectHomeNum; i++) {
            roomUuids.append(selectHomeList.get(i).uuid);
            if (i != selectHomeList.size() - 1) {
                roomUuids.append(",");
            }
        }

        // 联系人的
        StringBuffer passengerUuids = new StringBuffer();
        for (int i = 0; i < selectHomeNum; i++) {
            passengerUuids.append(selectedTravellerList.get(i).uuid);
            if (i != selectedTravellerList.size() - 1) {
                passengerUuids.append(",");
            }
        }
        // 待选择房间的
        StringBuffer orderDetailUuids = new StringBuffer();
        for (int i = 0; i < selectHomeNum; i++) {
            orderDetailUuids.append(orderDetailUuidslist.get(i));
            if (i != orderDetailUuidslist.size() - 1) {
                orderDetailUuids.append(",");
            }
        }


        chooseRoom(select_type, orderDetailUuids.toString(), roomUuids.toString(), passengerUuids.toString());
    }

    private void chooseRoom(final int select_type, String orderDetailUuids, String roomUuids, String passengerUuids) {
        HashMap<String, Object> h1 = new HashMap<>();

//        token	String	会员调用登录接口后，返回的唯一标识	是
//        sessionId	String	会员调用登录接口后，返回的sessionId	是
//        nowPage	String	当前页数	否
//        pageShow	String	每页条数	否
//        orderDetailUuids	String	预订单明细集合（多个逗号分隔）	是
//        roomUuids	String	房间uuid集合（多个逗号分隔）	是
//        passengerUuids	String	旅客uuid集合（多个逗号分隔，数量和房间对应）	是
//        orderUuid	String	预订单uuid（预订人办理传递）	否

        h1.put("token", SharePrefUtil.getString(mContext, ShareKeys.Token, ""));
        h1.put("sessionId", SharePrefUtil.getString(mContext, ShareKeys.sessionId, ""));
        h1.put("orderDetailUuids", orderDetailUuids);
        h1.put("roomUuids", roomUuids);             // 房间uuid集合（多个逗号分隔，数量和房间对应）
        h1.put("passengerUuids", passengerUuids);   // 旅客uuid集合（多个逗号分隔，数量和房间对应）
        h1.put("orderUuid", orderDetailUuid);       // 预订单uuid（预订人办理传递）
        Call<HttpResult<String>> call = service.chooseRoom(JsonUtils.convertParam("chooseRoom", h1));
        call.enqueue(new CallbackImpl<String>() {
            @Override
            public void responseSuccess(Call<HttpResult<String>> call, Response<HttpResult<String>> response) {
                if (select_type == SelectPeopleActivity.SELECT_MULTI_OF_ONE
                        || select_type == SelectPeopleActivity.SELECT_MULTI
                        || select_type == SelectPeopleActivity.SELECT_SIGNAL
                        ) {
                    EventBus.getDefault().post(EventBusKeys.endSelectHomeMulti);
                    finish();
                } else if (select_type == SelectPeopleActivity.SELECT_SIGNAL) {
                    // TODO: 2017/9/24  一人房间，选完房后就直接去支付？

                }
            }

            @Override
            protected void onRequestFinish() {
                super.onRequestFinish();
            }
        });
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(String event) {
        if (EventBusKeys.hadPayCheckIn.equals(event)) {
            mContext.onBackPressed();
        }

        if (EventBusKeys.hadSelectQuery.equals(event)) {
            LogUtil.e("xyd", "接收到的信息是" + event);
            getOptionalRoomList();
        }
    }


}
